package ws

import (
	. "nightowl/svc/run"
	"nightowl/logger"
	"bufio"
	"encoding/json"
	"io"
	"log"
	"os"
	"strings"
	"time"
)

type LogMessage struct {
	ClientID  string `json:"clientId,omitempty"`
	StepId  uint64 `json:"stepId,omitempty"`
	LineNo	uint32 `json:"LineNo"`
	Content   string `json:"content"`

}

type StepRunLogReader struct {
	requestArg RequestLogArg
	filePath    string
	stopChan    chan struct{}
	lastReadPos int64
}

func NewStepRunLogReader(requestArg RequestLogArg) *StepRunLogReader {
	stepRun := DeliveryRunSvc.GetStepRunById(requestArg.StepId)
	if stepRun == nil {
		logger.Info("NewStepRunLogReader|stepRun is null|:%s", DeliveryRunSvc.TaskRuns)
		return nil
	}
	filePath := stepRun.LogFile
	logger.Info("NewStepRunLogReader|logFile:%s", filePath)
	return &StepRunLogReader{
		requestArg: requestArg,
		filePath: filePath,
		stopChan: make(chan struct{}),
		lastReadPos: 0,
	}
}

func (r *StepRunLogReader) ReadLogs(sendChan chan<- []byte) {
	defer close(sendChan)

	file, err := os.Open(r.filePath)
	if err != nil {
		log.Printf("无法打开日志文件: %v", err)
		return
	}
	defer file.Close()

	// 初次读取定位到文件末尾
	if _, err := file.Seek(0, io.SeekEnd); err != nil {
		log.Printf("文件定位错误: %v", err)
		return
	}

	reader := bufio.NewReader(file)
	var lineNo uint32
	for {
		select {
		case <-r.stopChan:
			return
		default:
			// 检查文件是否有新内容
			fileInfo, err := file.Stat()
			if err != nil {
				log.Printf("获取文件信息错误: %v", err)
				time.Sleep(1 * time.Second)
				continue
			}

			if fileInfo.Size() > r.lastReadPos {
				// 读取新增内容
				file.Seek(r.lastReadPos, io.SeekStart)
				scanner := bufio.NewScanner(reader)

				for scanner.Scan() {
					line := scanner.Text()
					//跳过空行
					if r.shouldSkipLine(line) {
						continue
					}
					lineNo = lineNo + 1
					logMsg := &LogMessage{
				 		Content:   line,
				 		ClientID: r.requestArg.ClientID,
				 		StepId: r.requestArg.StepId,
				 		LineNo: lineNo,
					}
					jsonMsg, err := json.Marshal(logMsg)
					if err != nil {
						log.Printf("JSON编码错误: %v", err)
						continue
					}

					select {
					case sendChan <- jsonMsg:
					case <-r.stopChan:
						return
					default:
						log.Printf("客户端 %s 通道已满，丢弃消息", r.requestArg.ClientID)
					}
				}

				r.lastReadPos, _ = file.Seek(0, io.SeekCurrent)
			}

			time.Sleep(500 * time.Millisecond) // 降低CPU使用率
		}
	}
}

func (r *StepRunLogReader) shouldSkipLine(line string) bool {
	// 跳过空行
	return len(strings.TrimSpace(line)) == 0
}
func (r *StepRunLogReader) HandleCommand(cmd []byte) {
	// 处理客户端指令
	var data map[string]string
	if err := json.Unmarshal(cmd, &data); err != nil {
		return
	}

	
}

func (r *StepRunLogReader) Stop() {
	close(r.stopChan)
}